import json
import time

from loguru import logger

from com.arcfox.base.base_spider import ExecuteType
from com.arcfox.util import async_request as requests
from com.arcfox.yiqing.parser.yiqing_parser import YiQingParser
from com.arcfox.yiqing.spider.yiqing_base_spider import YiQingBaseSpider
from com.arcfox.yiqing.task.yiqing_task import YiQingTask


class RiskAreaSpider(YiQingBaseSpider):

    def __init__(self):
        super().__init__()
        self.url = "https://bmfw.www.gov.cn/bjww/interface/interfaceJson"
        self.parser = YiQingParser()
        self.task = YiQingTask()
        self.session = None

    async def _pull_task(self):
        return True, ExecuteType.ONCE

    async def _crawl_by_task(self, task):
        await self.__crawl_risk_area_data()

    async def __crawl_risk_area_data(self):
        self.cur_timestamp = str(int(time.time()))
        base_params = self.get_base_params(self.cur_timestamp)
        base_params.update({
            'key': "3C502C97ABDA40D0A60FBEE50FAAD1DA"
        })
        logger.info(base_params)
        response = await requests.post_with_session(self.url, headers=self.get_headers(), data=json.dumps(base_params))
        result_json = response.json()
        logger.info(result_json)
        if result_json['code'] == 0:
            data = result_json['data']
            await self.parser.remove_old_risk_area()
            await self.parser.save_risk_area(data)
